package com.tutu.service.impl;

import com.tutu.controller.CommonsController;
import com.tutu.core.Constant;
import com.tutu.core.api.DataApiUrls;
import com.tutu.entity.DeviceData;
import com.tutu.entity.vo.CodeDictVo;
import com.tutu.entity.vo.DataVo;
import com.tutu.service.CodeDictService;
import com.tutu.service.DeviceDataService;
import com.tutu.utils.*;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * DeviceDataServiceImpl
 */
@Service
public class DeviceDataServiceImpl implements DeviceDataService {

    @Autowired
    CodeDictService codeDictService;

    @Override
    public Map<String, Object> pageByParams(Integer deviceId, String keyWord, Integer pageNum, Integer pageSize) {
        return HttpRequestUtil.getOnlyData(DataApiUrls.base_prefix + DataApiUrls.page, "keyWord=" + UnicodeUtil.unicodeEncode(keyWord) + "&pageNum=" + pageNum + "&pageSize=" + pageSize + (null == deviceId ? ("&deviceId=" + deviceId) : ""));
    }

    @Override
    public Map<String, Object> getInfoById(Integer id) {
        return HttpRequestUtil.getCompleteData(DataApiUrls.base_prefix + DataApiUrls.info, "id=" + id);
    }

    @Override
    public Map<String, Object> deleteById(HttpServletRequest request, Integer id) {
        return HttpRequestUtil.getCompleteData(DataApiUrls.base_prefix + DataApiUrls.delete, "id=" + id);
    }

    @Override
    public Map<String, Object> batchDel(HttpServletRequest request, String ids) {
        return HttpRequestUtil.getCompleteData(DataApiUrls.base_prefix + DataApiUrls.batchDel, "ids=" + ids);
    }

    @Override
    public Map<String, Object> getInfoByDeviceCodeAndType(String deviceCode, Integer type) {
        Map<String, Object> map = HttpRequestUtil.getOnlyData(DataApiUrls.base_prefix + DataApiUrls.getLastData, "deviceCode=" + deviceCode + "&type=" + type);

        if (map.containsKey("valueList") && !(map.get("valueList") + "").equals("[]")) {
            JSONArray valueList = JSONArray.fromObject(map.get("valueList"));
            JSONArray finallyList = new JSONArray();
            Map<String, Object> tempMap;

            // 根据缓存的设备参数列表自动匹配对应的中文释义
            for (Object o : valueList) {
                tempMap = JsonUtil.json2Map(o);

                if (isNeedJump(tempMap.get("code"))) continue;

                finallyList.add(tempMap);
            }

            map.put("valueList", finallyList);

            List<CodeDictVo> codeDictVoList = new ArrayList<>();
            CodeDictVo cdv;
            Map<String, Object> tm;

            for (Object o : finallyList) {
                tm = JsonUtil.json2Map(o);
                cdv = new CodeDictVo();

                cdv.setType(type + "");
                cdv.setCode(tm.get("code") + "");
                cdv.setName(tm.get("name") + "");
                cdv.setUnit(tm.get("unit") + "");
                cdv.setValue(tm.get("value") + "");

                if (cdv.getCode().equals("CP_DataTime")) {
                    cdv.setStatus(Constant.CHECK_STATUS_SUCCESS);
                } else {
                    cdv.setStatus(Integer.parseInt(tm.get("status") + ""));
                }

                codeDictVoList.add(cdv);
            }

            CommonsController.deviceCodeDictMap.put(deviceCode + "_" + type, codeDictVoList);
        }

        return map;
    }

    @Override
    public List<DeviceData> productExcel(Map<String, String> map) {
        String searchDate = map.get("searchDate");
        int type = Integer.parseInt(map.get("type"));
        String keyWord = map.get("keyWord");

        List<DeviceData> deviceDataList = new ArrayList<>();

        Map<String, Object> deviceMap = new HashMap<>();

        for (List<Map<String, Object>> deviceList : CommonsController.baseDeviceList.values())
            for (Map<String, Object> tempMap : deviceList)
                if (tempMap.get("code").equals(map.get("deviceCode"))) {
                    deviceMap = tempMap;

                    break;
                }

        if (deviceMap.size() > 0) {
            // 获取对应的设备数据
            Map<String, Object> dataMap = HttpRequestUtil.getOnlyData(DataApiUrls.base_prefix + DataApiUrls.pageByBackendParams, "keyWord=" + UnicodeUtil.unicodeEncode(keyWord) + "&pageNum=1&pageSize=100000&deviceCode=" + deviceMap.get("code") + "&type=" + type + "&searchDate=" + (BaseUtil.isBlank(searchDate) ? DateUtils.getTime() : searchDate));
            Map<String, Object> tempMap;
            Map<String, Object> valueMap;
            DeviceData dd;

            if (dataMap.containsKey("list") && (dataMap.get("list") + "").length() > 5) {
                for (Object obj : JSONArray.fromObject(dataMap.get("list"))) {
                    tempMap = JsonUtil.json2Map(obj);

                    // 开始写入内容
                    dd = new DeviceData();
                    dd.setType(Integer.parseInt(tempMap.get("type") + ""));
                    dd.setDeviceName(tempMap.get("deviceName") + "");
                    dd.setCreateTime(tempMap.get("createTime") + "");

                    for (Object valueObj : JSONArray.fromObject(tempMap.get("valueList"))) {
                        valueMap = JsonUtil.json2Map(valueObj);

                        dd.getValueList().add(new DataVo(valueMap.get("code") + "", valueMap.get("name") + "", valueMap.get("value") + ""));
                    }

                    deviceDataList.add(dd);
                }
            }
        }

        return deviceDataList;
    }

    @Override
    public Map<String, Object> changeDeviceCodeStatus(HttpServletRequest request, String deviceCode, Integer type, String codeDictCode, Integer status, boolean isRefreshCache) {
        return HttpRequestUtil.getCompleteData(DataApiUrls.base_prefix + DataApiUrls.updateDeviceCodeStatus, "deviceCode=" + deviceCode + "&type=" + type + "&codeDictCode=" + codeDictCode + "&status=" + status);
    }

    @Override
    public Map<String, Object> changeDeviceCodeName(HttpServletRequest request, String deviceCode, Integer type, String codeDictCode, String content) {
        Map<String, Object> map = HttpRequestUtil.getCompleteData(DataApiUrls.base_prefix + DataApiUrls.updateDeviceCodeName, "deviceCode=" + deviceCode + "&type=" + type + "&codeDictCode=" + codeDictCode + "&content=" + UnicodeUtil.unicodeEncode(content));

        codeDictService.loadCacheData();

        return map;
    }

    // 检测设备参数是否需要跳过显示
    boolean isNeedJump(Object o) {
        return (o + "").contains("SampleTime") || (o + "").contains("Flag") || (o + "").equals("time");
    }
}